<template>
  <div class="quality-inspection-container page-common-layout">
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <AssociativeSelectGroup
            :map="selectMap"
            @conditionChange="selectGroupChange($event)"
            :orgTypeValue="1"
          >
          </AssociativeSelectGroup>
        </template>
        <template slot="operate"> </template>
      </ScreenConditions>
    </div>
    <div class="hazard-body-container">
      <div class="operate">
        <a-button
          @click="handleAdd()"
          class="cu-btn-primary margin-bottom-xs"
          icon="plus"
          v-if="showButton"
          v-action:zlxc_add
        >
          新增
        </a-button>
      </div>
      <div class="main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
        >
          <vxe-column type="seq" width="80" title="序号"></vxe-column>
          <vxe-column field="checkName" title="检查名称"> </vxe-column>
          <vxe-column field="checkTypeDesc" title="检查类型"> </vxe-column>
          <vxe-column field="checkDepartmentName" title="检查单位">
          </vxe-column>
          <vxe-column field="checkTimeStart" title="检查开始时间"> </vxe-column>
          <vxe-column field="checkTimeEnd" title="检查结束时间"> </vxe-column>
          <vxe-column title="状态">
            <template #default="{ row }">
              <span :class="checkClass(row.approveStatus)">
                {{ checkStatus(row.approveStatus) }}
              </span>
            </template>
          </vxe-column>
          <vxe-column
            field="operate"
            width="250"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-button type="link" @click="gotoDetail(row)">
                  查看
                </a-button>
                <a-button
                  type="link"
                  @click="handelSubmit(row)"
                  v-if="showButton && row.approveStatus != 2"
                  :loading="submitLoading"
                  v-action:zlxc_edit
                >
                  提交
                </a-button>
                <a-button
                  type="link"
                  @click="editor(row)"
                  v-if="showButton && row.approveStatus != 2"
                  v-action:zlxc_edit
                >
                  编辑
                </a-button>
                <a-button
                  type="link"
                  class="danger"
                  @click="handleDelClick(row)"
                  v-if="showButton && row.approveStatus != 2"
                  v-action:zlxc_delete
                >
                  删除
                </a-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="pager-container">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>

    <!-- 编辑弹窗-->
    <edit-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :url="url"
      requestMethod="post"
      :tableDataType="tableDataType"
      @cancel="handleCancel()"
      @ok="handleOk()"
    />
    <!-- 详情 -->
    <detail
      :visible.sync="detailModalVisible"
      :soucre="dataSoucre"
      @cancel="detailCancel()"
    ></detail>
  </div>
</template>

<script>
//质量巡查
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import AssociativeSelectGroup from "@/components/extendCustom/AssociativeSelectGroup";
import editForm from "@/pages/form/formPreview/edit.vue";
import detail from "@/pages/customPage/components/inspectDetail";
import {
  pageHazard,
  deleteHazard,
  submitHazard,
  getTaskPermission,
} from "@/api/safetyManage";
export default {
  components: {
    ScreenConditions,
    AssociativeSelectGroup,
    editForm,
    detail,
  },
  provide() {
    // 使用函数的形式，可以访问到 `this`
    return {
      extraParamsValue: () => this.extraParams,
    };
  },
  data() {
    return {
      showButton: false,
      selectMap: [
        //项目
        {
          type: "proCode",
          mode: "default",
          placeholder: "请选择项目",
          isDefault: true,
        },
        //标段
        {
          type: "orgCode",
          mode: "default",
          placeholder: "请选择标段",
          allowClear: true,
        },
      ],
      conditionsData: {},
      extraParams: {},
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      visible: false,
      confirmLoading: false,
      url: {
        save: "/form/formDatabase/formSave",
        update: "/form/formDatabase/formUpdate",
      },
      tableDataType: "",
      tableUuid: "F11CDF488D514BD19DF4B87C993196A0",
      detailModalVisible: false,
      dataSoucre: {},
      submitLoading: false,
    };
  },
  mounted() {},
  methods: {
    selectGroupChange(data) {
      this.dealConditionsData(data);
      this.pager.page = 1;
      this.getTableData();
      this.getPermission();
    },
    //处理搜索区域选中值
    dealConditionsData(data = {}) {
      Object.keys(data).forEach((key) => {
        if (!data[key]) {
          this.conditionsData[key] = "";
        } else if (Array.isArray(data[key])) {
          this.conditionsData[key] = data[key]
            .map((v) => v.key)
            .filter((v) => v)
            .toString();
        } else if (
          Object.prototype.toString.call(data[key]) === "[object Object]"
        ) {
          this.conditionsData[key] = data[key].key;
        } else {
          this.conditionsData[key] = "";
        }
      });
    },

    //查询操作权限
    getPermission() {
      return new Promise((reslove, reject) => {
        let { proCode } = this.conditionsData;
        getTaskPermission({ tenantCode: proCode, type: 2 })
          .then((res) => {
            this.showButton = res?.data ?? false;
            reslove();
          })
          .catch((_) => {
            this.showButton = false;
            reject();
          });
      });
    },
    checkStatus(key) {
      switch (key) {
        case "1":
          return "未提交";
        case "2":
          return "已提交";

        default:
          return "-";
      }
    },
    checkClass(key) {
      switch (key) {
        case "1":
          return "no";
        case "2":
          return "status";

        default:
          return "";
      }
    },

    //详情
    gotoDetail(row) {
      let { proCode } = this.conditionsData;
      let { uuid } = row;
      this.dataSoucre = {
        uuid,
        tenantCode: proCode,
        type: 2,
      };
      this.detailModalVisible = true;
    },

    //详情关闭
    detailCancel() {
      this.detailModalVisible = false;
      this.getTableData();
    },

    //查询列表数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let { proCode, orgCode = "" } = this.conditionsData;
      pageHazard({
        page,
        pageSize,
        tenantCode: proCode,
        checkDepartmentCode: orgCode,
        type: 2,
      })
        .then((res) => {
          this.tableData = res?.rows || [];
          this.pager.total = res?.totalCount || 0;
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        })
        .finally((_) => {
          this.loading = false;
        });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },

    // 新增
    async handleAdd() {
      this.modalFooter = {};
      let { proCode } = this.conditionsData;
      this.extraParams = {
        pro_code: proCode,
      };
      this.visible = true;
      this.$refs.createModal.title = "新增";
      let formJsonData = await this.loadDataJson(this.tableUuid);
      let { addApiUrl } = JSON.parse(formJsonData)?.config ?? {};
      this.url.save = addApiUrl ?? "/form/formDatabase/formSave";
      this.$refs.createModal.loadData(this.tableUuid, "add", formJsonData);
    },

    //编辑
    async editor(record = {}) {
      let { uuid } = record;
      let { proCode } = this.conditionsData;
      this.extraParams = {
        pro_code: proCode,
      };
      this.visible = true;
      let formJsonData = await this.loadDataJson(this.tableUuid);
      let { editApiUrl } = JSON.parse(formJsonData)?.config ?? {};
      this.url.update = editApiUrl ?? "/form/formDatabase/formSave";
      this.$refs.createModal.title = "编辑";
      this.$refs.createModal.loading = true;
      this.$post("/form/formDatabase/formGetDetail", {
        uuid: uuid,
        formUuid: this.tableUuid,
      }).then((res) => {
        this.$refs.createModal.loadData(
          this.tableUuid,
          "edit",
          formJsonData,
          res
        );
      });
    },

    dealData(disabled = false, formJsonData = "{}") {
      let dealData = JSON.parse(formJsonData);
      let { list = [] } = dealData;
      list.forEach((v) => {
        let { columns = [], options } = v;
        if (options) {
          options.disabled = disabled;
        }
        columns.forEach((item) => {
          let { list = [] } = item;
          list.forEach((c) => {
            let { options } = c;
            options.disabled = disabled;
          });
        });
      });
      return JSON.stringify(dealData);
    },

    loadDataJson(tableUuid = "") {
      return new Promise((reslove) => {
        this.$post("/form/formBasicConfigure/getDetailByUuid", {
          uuid: tableUuid,
        })
          .then((res) => {
            this.tableDataType = res.formDatabase?.type || "";
            reslove(res.formDesign.designJson);
          })
          .catch((_) => {
            reslove({});
          });
      });
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          deleteHazard({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },
    //提交
    handelSubmit(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定提交该数据吗？",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          that.submitLoading = true;
          submitHazard({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("提交成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {})
            .finally((_) => {
              that.submitLoading = false;
            });
        },
      });
    },

    //关闭弹窗
    handleCancel() {
      this.visible = false;
    },

    handleOk() {
      this.visible = false;
      this.getTableData();
    },
  },
};
</script>

<style lang="less" scoped>
.quality-inspection-container {
  display: flex;
  flex-direction: column;
  .hazard-body-container {
    flex: 1;
    background-color: @base-bg-color;
    flex-shrink: 0;
    position: relative;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .operate {
      display: flex;
    }
    .main {
      flex: 1;
      .status {
        color: #4bc964;
      }
      .no {
        color: #1677ff;
      }
    }
    .pager-container {
      flex-shrink: 0;
      box-sizing: border-box;
    }
  }
}
</style>
